﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WebChatService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class WebChatService : IWebChatService
    {
        public string[] GetChannels()
        {
            WebChatEntities dbContext = new WebChatEntities();
            using (dbContext)
            {
                var channels = from ch in dbContext.Channels
                               select ch.ChannelName;
                return channels.ToArray();
            }
        }

        public string[] GetChannelMessages(int channelID)
        {
            WebChatEntities dbContext = new WebChatEntities();
            using (dbContext)
            {
                var messages = from msg in dbContext.Messages
                               where msg.ChannelID==channelID
                               select msg.Message1;
                return messages.ToArray();
            }
        }

        public void CreateNewChannel(string channelName)
        { 
            WebChatEntities dbContext = new WebChatEntities();
            using (dbContext)
            {
                Channel existing = dbContext.Channels.FirstOrDefault(ch => ch.ChannelName == channelName);
                bool channelExists = existing != null;
                if (channelExists)
                {
                    var messages = from msg in dbContext.Messages
                               where msg.ChannelID==existing.ChannelID
                               select msg;
                    foreach (var message in messages)
	                {
                        dbContext.Messages.DeleteObject(message);
	                }
                }
                else
                {
                    Channel newChannel = new Channel();
                    newChannel.ChannelName=channelName;
                    dbContext.Channels.AddObject(newChannel);
                }
            }
        }

        public void PostMessage(int channeldID, string message)
        { 
            WebChatEntities dbContext = new WebChatEntities();
            using (dbContext)
            {

            }
        }
    }
}
